<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单字段配置管理 - 项目管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../styles/common.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* Body and container styles are now in common.css */
        .container {
            margin: 0 auto;
        }

        /* Header styles are now in common.css */

        /* Navigation button styles are now in common.css */

        .mb-4 {
            margin-bottom: 1.5rem;
        }

        /* 覆盖导航按钮样式以提高可见性 */
        .nav-pills .nav-link {
            background: #f8f9fa !important;
            color: #495057 !important;
            border: 2px solid #dee2e6 !important;
            border-radius: 8px !important;
            padding: 12px 25px !important;
            margin: 0 8px !important;
            text-decoration: none !important;
            transition: all 0.3s ease !important;
            font-weight: 500 !important;
        }

        .nav-pills .nav-link:hover {
            background: #007bff !important;
            color: white !important;
            border-color: #007bff !important;
            transform: translateY(-1px) !important;
            box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3) !important;
        }

        .nav-pills .nav-link.active {
            background: #007bff !important;
            color: white !important;
            border-color: #007bff !important;
            font-weight: 600 !important;
        }

        .content {
            padding: 40px;
        }

        .form-section {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
        }

        .form-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }

        .form-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .checkbox-group {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .checkbox-item {
            display: flex;
            align-items: center;
            padding: 15px;
            background: white;
            border-radius: 12px;
            border: 2px solid #e1e5e9;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .checkbox-item:hover {
            border-color: #667eea;
        }

        .checkbox-item input[type="checkbox"] {
            margin-right: 10px;
            transform: scale(1.2);
        }

        .btn {
            background: #007bff;
            color: white;
            border: 2px solid #007bff;
            padding: 12px 30px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
            margin-right: 10px;
        }

        .btn:hover {
            background: #0056b3;
            border-color: #0056b3;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            border: 2px solid #6c757d;
        }

        .btn-secondary:hover {
            background: #545b62;
            border-color: #545b62;
        }

        .btn-danger {
            background: #dc3545;
            border: 2px solid #dc3545;
        }

        .btn-danger:hover {
            background: #c82333;
            border-color: #c82333;
        }

        .config-list {
            margin-top: 30px;
        }

        .config-item {
            background: white;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }

        .config-item:hover {
            border-color: #667eea;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .config-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .config-name {
            font-size: 1.2em;
            font-weight: 600;
            color: #333;
        }

        .config-fields {
            color: #666;
            margin-bottom: 10px;
        }

        .config-actions {
            display: flex;
            gap: 10px;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .success {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background-color: white;
            margin: 0;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
            position: relative;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: #000;
        }

        .field-type-item {
            background: white;
            border: 2px solid #e1e5e9;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .field-type-item:hover {
            border-color: #667eea;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.15);
            transform: translateY(-2px);
        }

        .field-type-info {
            flex: 1;
        }

        .field-type-actions {
            display: flex;
            gap: 10px;
        }

        .btn-small {
            padding: 5px 15px;
            font-size: 14px;
            border-radius: 6px;
        }

        .btn-small.btn-secondary {
            background: #6c757d;
            border: 2px solid #6c757d;
        }

        .btn-small.btn-danger {
            background: #dc3545;
            border: 2px solid #dc3545;
        }

        /* 导航返回按钮样式 */
        .nav-btn {
            background: #28a745;
            color: white;
            border: 2px solid #28a745;
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
            display: inline-block;
        }

        .nav-btn:hover {
            background: #218838;
            border-color: #218838;
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
        }

        .form-row {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
        }

        .form-row .form-group {
            flex: 1;
            margin-bottom: 0;
        }

        select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        select:focus {
            outline: none;
            border-color: #667eea;
        }

        /* 响应式设计优化 */
        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }
            
            .header {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 2em;
            }
            
            .content {
                padding: 20px;
            }
            
            .form-section {
                padding: 20px;
            }
            
            .nav-pills {
                flex-direction: column;
                align-items: center;
            }
            
            .nav-pills .nav-link {
                margin: 5px 0;
                width: 200px;
                text-align: center;
            }
            
            .checkbox-group {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            
            .form-row {
                flex-direction: column;
                gap: 0;
            }
            
            .config-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }
            
            .config-actions {
                width: 100%;
                justify-content: flex-start;
            }
            
            .field-type-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }
            
            .field-type-actions {
                width: 100%;
                justify-content: flex-start;
            }
            
            .modal-content {
                margin: 10% auto;
                padding: 20px;
                width: 95%;
            }
        }
        
        @media (max-width: 480px) {
            .header h1 {
                font-size: 1.8em;
            }
            
            .content {
                padding: 15px;
            }
            
            .form-section {
                padding: 15px;
            }
            
            .btn {
                padding: 10px 20px;
                font-size: 14px;
            }
            
            .nav-pills .nav-link {
                width: 100%;
                margin: 3px 0;
            }
        }
    </style>
</head>
<body>
    <!-- 统一导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <span class="navbar-brand">
                <i class="bi bi-gear-fill me-2"></i>
                表单字段配置管理
            </span>
            <div class="navbar-nav ms-auto">
                <div class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                        <i class="bi bi-person-circle me-1"></i>
                        <span id="navbar-username">加载中...</span>
                    </a>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="#" onclick="logout()">
                            <i class="bi bi-box-arrow-right me-2"></i>退出登录
                        </a></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="header">
            <h1>
                <i class="bi bi-ui-checks-grid me-3"></i>
                表单字段配置管理
            </h1>
            <p>管理表单字段配置模板</p>
            
            <div class="mb-4">
                <nav class="nav nav-pills">
                    <a class="nav-link" href="admin-config.html">
                        <i class="bi bi-people me-2"></i>
                        管理员配置
                    </a>
                    <a class="nav-link active" href="form-config-management.html">
                        <i class="bi bi-ui-checks-grid me-2"></i>
                        表单字段配置
                    </a>
                    <a class="nav-link" href="project-management.html">
                        <i class="bi bi-folder me-2"></i>
                        项目管理
                    </a>
                </nav>
            </div>
            
            <div class="nav-buttons">
                <a href="/pages/admin.html" class="nav-btn">
                    <i class="bi bi-arrow-left me-2"></i>
                    返回管理页面
                </a>
            </div>
        </div>

        <div class="content">
            <div id="message"></div>

            <!-- 字段类型管理 -->
            <div class="form-section">
                <h2>
                    <i class="bi bi-collection me-2"></i>
                    字段类型管理
                </h2>
                <div style="margin-bottom: 20px;">
                    <button class="btn" onclick="showAddFieldTypeModal()">
                        <i class="bi bi-plus-circle me-2"></i>
                        添加新字段类型
                    </button>
                    <button class="btn btn-secondary" onclick="initializeDefaultFields()">
                        <i class="bi bi-arrow-clockwise me-2"></i>
                        初始化默认字段
                    </button>
                </div>
                <div id="fieldTypesList"></div>
            </div>

            <!-- 创建新配置 -->
            <div class="form-section">
                <h2>
                    <i class="bi bi-file-earmark-plus me-2"></i>
                    创建新的表单配置
                </h2>
                <form id="configForm">
                    <div class="form-group">
                        <label for="configName">配置名称:</label>
                        <input type="text" id="configName" name="name" required placeholder="例如：基础信息收集">
                    </div>

                    <div class="form-group">
                        <label>选择需要的字段:</label>
                        <div id="dynamicFieldsContainer" class="checkbox-group">
                            <!-- 动态加载的字段选项 -->
                        </div>
                    </div>

                    <button type="submit" class="btn">
                        <i class="bi bi-check-circle me-2"></i>
                        创建配置
                    </button>
                    <button type="button" class="btn btn-secondary" onclick="resetForm()">
                        <i class="bi bi-arrow-counterclockwise me-2"></i>
                        重置
                    </button>
                </form>
            </div>

            <!-- 现有配置列表 -->
            <div class="form-section">
                <h2>
                    <i class="bi bi-list-ul me-2"></i>
                    现有配置
                </h2>
                <div id="loading" class="loading" style="display: none;">加载中...</div>
                <div id="configList" class="config-list"></div>
            </div>
        </div>
    </div>

    <!-- 添加字段类型模态框 -->
    <div id="addFieldTypeModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeAddFieldTypeModal()">&times;</span>
            <h2>
                <i class="bi bi-plus-square me-2"></i>
                添加新字段类型
            </h2>
            <form id="fieldTypeForm">
                <div class="form-row">
                    <div class="form-group">
                        <label for="fieldKey">字段键名:</label>
                        <input type="text" id="fieldKey" name="key" required placeholder="例如：email">
                    </div>
                    <div class="form-group">
                        <label for="fieldLabel">字段标签:</label>
                        <input type="text" id="fieldLabel" name="label" required placeholder="例如：邮箱地址">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="fieldType">字段类型:</label>
                        <select id="fieldType" name="type" required>
                            <option value="text">文本</option>
                            <option value="email">邮箱</option>
                            <option value="tel">电话</option>
                            <option value="number">数字</option>
                            <option value="textarea">多行文本</option>
                            <option value="select">下拉选择</option>
                            <option value="radio">单选</option>
                            <option value="checkbox">多选</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="sortOrder">排序:</label>
                        <input type="number" id="sortOrder" name="sortOrder" min="1" value="1">
                    </div>
                </div>
                <div class="form-group">
                    <label for="fieldOptions">选项 (仅用于下拉/单选/多选，每行一个):</label>
                    <textarea id="fieldOptions" name="options" rows="3" placeholder="选项1\n选项2\n选项3"></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="fieldRequired" name="required"> 必填字段
                        </label>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="fieldEnabled" name="enabled" checked> 启用字段
                        </label>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="closeAddFieldTypeModal()">取消</button>
                    <button type="submit" class="btn">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑字段类型模态框 -->
    <div id="editFieldTypeModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeEditFieldTypeModal()">&times;</span>
            <h2>编辑字段类型</h2>
            <form id="editFieldTypeForm">
                <input type="hidden" id="editFieldId" name="id">
                <div class="form-row">
                    <div class="form-group">
                        <label for="editFieldKey">字段键名:</label>
                        <input type="text" id="editFieldKey" name="key" required placeholder="例如：email">
                    </div>
                    <div class="form-group">
                        <label for="editFieldLabel">字段标签:</label>
                        <input type="text" id="editFieldLabel" name="label" required placeholder="例如：邮箱地址">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="editFieldType">字段类型:</label>
                        <select id="editFieldType" name="type" required>
                            <option value="text">文本</option>
                            <option value="email">邮箱</option>
                            <option value="tel">电话</option>
                            <option value="number">数字</option>
                            <option value="textarea">多行文本</option>
                            <option value="select">下拉选择</option>
                            <option value="radio">单选</option>
                            <option value="checkbox">多选</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="editSortOrder">排序:</label>
                        <input type="number" id="editSortOrder" name="sortOrder" min="1" value="1">
                    </div>
                </div>
                <div class="form-group">
                    <label for="editFieldOptions">选项 (仅用于下拉/单选/多选，每行一个):</label>
                    <textarea id="editFieldOptions" name="options" rows="3" placeholder="选项1\n选项2\n选项3"></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="editFieldRequired" name="required"> 必填字段
                        </label>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="editFieldEnabled" name="enabled"> 启用字段
                        </label>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="closeEditFieldTypeModal()">取消</button>
                    <button type="submit" class="btn">更新</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 检查认证
        async function checkAuth() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/pages/login.html';
                return null;
            }
            
            try {
                // 获取当前用户信息
                const response = await fetch('/auth/profile', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取用户信息失败');
                }
                
                const user = await response.json();
                
                // 保存用户信息到localStorage，供其他函数使用
                localStorage.setItem('currentUser', JSON.stringify(user));
                
                return { token, user };
            } catch (error) {
                console.error('认证检查失败:', error);
                localStorage.removeItem('token');
                localStorage.removeItem('currentUser');
                window.location.href = '/pages/login.html';
                return null;
            }
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('username');
            window.location.href = '/pages/login.html';
        }

        // 加载用户信息
        async function loadUserInfo() {
            const token = localStorage.getItem('token');
            if (!token) return;
            
            try {
                const response = await fetch('/users/profile', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const user = await response.json();
                    document.getElementById('navbar-username').textContent = user.username;
                    // 同时保存到localStorage以备后用
                    localStorage.setItem('username', user.username);
                } else {
                    // 如果API调用失败，尝试从localStorage读取
                    const username = localStorage.getItem('username');
                    if (username) {
                        document.getElementById('navbar-username').textContent = username;
                    }
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                // 如果API调用失败，尝试从localStorage读取
                const username = localStorage.getItem('username');
                if (username) {
                    document.getElementById('navbar-username').textContent = username;
                }
            }
        }

        // 显示消息
        function showMessage(message, type = 'success') {
            const messageDiv = document.getElementById('message');
            messageDiv.innerHTML = `<div class="${type}">${message}</div>`;
            setTimeout(() => {
                messageDiv.innerHTML = '';
            }, 5000);
        }

        // 加载配置列表
        async function loadConfigs() {
            const token = checkAuth();
            if (!token) return;

            document.getElementById('loading').style.display = 'block';
            
            try {
                const response = await fetch('/form-config', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    const configs = await response.json();
                    displayConfigs(configs);
                } else {
                    showMessage('加载配置失败', 'error');
                }
            } catch (error) {
                console.error('加载配置失败:', error);
                showMessage('加载配置失败', 'error');
            } finally {
                document.getElementById('loading').style.display = 'none';
            }
        }

        // 全局变量存储字段类型
        let fieldTypes = [];

        // 加载字段类型
        async function loadFieldTypes() {
            const authResult = await checkAuth();
            if (!authResult) return;
            const { token } = authResult;

            try {
                const response = await fetch('/field-type', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    fieldTypes = await response.json();
                    displayFieldTypes();
                    updateDynamicFieldsContainer();
                } else {
                    showMessage('加载字段类型失败', 'error');
                }
            } catch (error) {
                console.error('加载字段类型失败:', error);
                showMessage('加载字段类型失败', 'error');
            }
        }

        // 显示字段类型列表
        function displayFieldTypes() {
            const container = document.getElementById('fieldTypesList');
            
            if (fieldTypes.length === 0) {
                container.innerHTML = '<p>暂无字段类型，请先初始化默认字段</p>';
                return;
            }

            container.innerHTML = fieldTypes.map(fieldType => `
                <div class="field-type-item">
                    <div class="field-type-info">
                        <strong>${fieldType.label}</strong> (${fieldType.key})
                        <br>
                        <small>类型: ${fieldType.type} | 排序: ${fieldType.sortOrder} | ${fieldType.required ? '必填' : '可选'} | ${fieldType.enabled ? '启用' : '禁用'}</small>
                    </div>
                    <div class="field-type-actions">
                        <button class="btn btn-secondary btn-small" onclick="editFieldType(${fieldType.id})">编辑</button>
                        <button class="btn btn-danger btn-small" onclick="deleteFieldType(${fieldType.id})">删除</button>
                    </div>
                </div>
            `).join('');
        }

        // 更新动态字段容器
        function updateDynamicFieldsContainer() {
            const container = document.getElementById('dynamicFieldsContainer');
            
            const enabledFieldTypes = fieldTypes.filter(ft => ft.enabled).sort((a, b) => a.sortOrder - b.sortOrder);
            
            container.innerHTML = enabledFieldTypes.map(fieldType => `
                <div class="checkbox-item">
                    <input type="checkbox" id="field-${fieldType.key}" name="fieldTypes" value="${fieldType.id}" ${fieldType.required ? 'checked' : ''}>
                    <label for="field-${fieldType.key}">${fieldType.label}</label>
                </div>
            `).join('');
        }

        // 显示配置列表
        function displayConfigs(configs) {
            const configList = document.getElementById('configList');
            
            if (configs.length === 0) {
                configList.innerHTML = '<p>暂无配置</p>';
                return;
            }

            configList.innerHTML = configs.map(config => {
                const fieldTypesText = config.fieldTypes ? config.fieldTypes.map(ft => ft.label).join('、') : '无字段';
                
                return `
                    <div class="config-item">
                        <div class="config-header">
                            <div class="config-name">${config.name}</div>
                            <div class="config-actions">
                                <button class="btn btn-secondary" onclick="editConfig(${config.id})">编辑</button>
                                <button class="btn btn-danger" onclick="deleteConfig(${config.id})">删除</button>
                            </div>
                        </div>
                        <div class="config-fields">包含字段: ${fieldTypesText}</div>
                        <div style="color: #999; font-size: 0.9em;">创建时间: ${new Date(config.createdAt).toLocaleString()}</div>
                    </div>
                `;
            }).join('');
        }

        // 创建配置
        async function createConfig(formData) {
            const token = checkAuth();
            if (!token) return;

            try {
                const response = await fetch('/form-config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(formData)
                });

                if (response.ok) {
                    showMessage('配置创建成功');
                    resetForm();
                    loadConfigs();
                } else {
                    const error = await response.json();
                    showMessage(error.message || '创建失败', 'error');
                }
            } catch (error) {
                console.error('创建配置失败:', error);
                showMessage('创建配置失败', 'error');
            }
        }

        // 字段类型管理函数
        function showAddFieldTypeModal() {
            document.getElementById('addFieldTypeModal').style.display = 'flex';
        }

        function closeAddFieldTypeModal() {
            document.getElementById('addFieldTypeModal').style.display = 'none';
            document.getElementById('fieldTypeForm').reset();
        }

        // 初始化默认字段
        async function initializeDefaultFields() {
            const authResult = await checkAuth();
            if (!authResult) return;
            const { token, user } = authResult;
            
            // 检查权限：只有级别1的管理员可以初始化字段类型
            if (user.level !== 1) {
                showMessage('权限不足：只有系统管理员（级别1）可以初始化字段类型', 'error');
                return;
            }

            try {
                const response = await fetch('/field-type/initialize', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    showMessage('默认字段初始化成功');
                    loadFieldTypes();
                } else {
                    const errorData = await response.json().catch(() => null);
                    if (response.status === 403) {
                        showMessage('权限不足：只有系统管理员（级别1）可以初始化字段类型', 'error');
                    } else if (errorData && errorData.message) {
                        showMessage(errorData.message, 'error');
                    } else {
                        showMessage('初始化失败', 'error');
                    }
                }
            } catch (error) {
                console.error('初始化失败:', error);
                showMessage('初始化失败', 'error');
            }
        }

        // 创建字段类型
        async function createFieldType() {
            const authResult = await checkAuth();
            if (!authResult) return;
            const { token, user } = authResult;
            
            // 检查权限：只有级别1的管理员可以创建字段类型
            if (user.level !== 1) {
                showMessage('权限不足：只有系统管理员（级别1）可以创建字段类型', 'error');
                return;
            }

            try {
                const response = await fetch('/field-type', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(formData)
                });

                if (response.ok) {
                    showMessage('字段类型创建成功');
                    closeAddFieldTypeModal();
                    loadFieldTypes();
                } else {
                    const errorData = await response.json().catch(() => null);
                    if (response.status === 403) {
                        showMessage('权限不足：只有系统管理员（级别1）可以创建字段类型', 'error');
                    } else if (errorData && errorData.message) {
                        showMessage(errorData.message, 'error');
                    } else {
                        showMessage('创建失败', 'error');
                    }
                }
            } catch (error) {
                console.error('创建字段类型失败:', error);
                showMessage('创建字段类型失败', 'error');
            }
        }

        // 删除字段类型
        async function deleteFieldType(id) {
            if (!confirm('确定要删除这个字段类型吗？')) {
                return;
            }

            const authResult = await checkAuth();
            if (!authResult) return;
            const { token, user } = authResult;
            
            // 检查权限：只有级别1的管理员可以删除字段类型
            if (user.level !== 1) {
                showMessage('权限不足：只有系统管理员（级别1）可以删除字段类型', 'error');
                return;
            }

            try {
                const response = await fetch(`/field-type/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    showMessage('字段类型删除成功');
                    loadFieldTypes();
                } else {
                    const errorData = await response.json().catch(() => null);
                    if (response.status === 403) {
                        showMessage('权限不足：只有系统管理员（级别1）可以删除字段类型', 'error');
                    } else if (errorData && errorData.message) {
                        showMessage(errorData.message, 'error');
                    } else {
                        showMessage('删除失败', 'error');
                    }
                }
            } catch (error) {
                console.error('删除字段类型失败:', error);
                showMessage('删除字段类型失败', 'error');
            }
        }

        // 编辑字段类型
        function editFieldType(id) {
            const fieldType = fieldTypes.find(ft => ft.id === id);
            if (!fieldType) {
                showMessage('字段类型不存在', 'error');
                return;
            }

            // 填充编辑表单
            document.getElementById('editFieldId').value = fieldType.id;
            document.getElementById('editFieldKey').value = fieldType.key;
            document.getElementById('editFieldLabel').value = fieldType.label;
            document.getElementById('editFieldType').value = fieldType.type;
            document.getElementById('editSortOrder').value = fieldType.sortOrder;
            document.getElementById('editFieldRequired').checked = fieldType.required;
            document.getElementById('editFieldEnabled').checked = fieldType.enabled;
            
            // 填充选项
            if (fieldType.options && fieldType.options.length > 0) {
                document.getElementById('editFieldOptions').value = fieldType.options.join('\n');
            } else {
                document.getElementById('editFieldOptions').value = '';
            }

            // 显示编辑模态框
            document.getElementById('editFieldTypeModal').style.display = 'flex';
        }

        // 关闭编辑字段类型模态框
        function closeEditFieldTypeModal() {
            document.getElementById('editFieldTypeModal').style.display = 'none';
            document.getElementById('editFieldTypeForm').reset();
        }

        // 更新字段类型
        async function updateFieldType(id, formData) {
            const authResult = await checkAuth();
            if (!authResult) return;
            const { token, user } = authResult;
            
            // 检查权限：只有级别1的管理员可以修改字段类型
            if (user.level !== 1) {
                showMessage('权限不足：只有系统管理员（级别1）可以修改字段类型', 'error');
                return;
            }

            try {
                const response = await fetch(`/field-type/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(formData)
                });

                if (response.ok) {
                    showMessage('字段类型更新成功');
                    closeEditFieldTypeModal();
                    loadFieldTypes();
                } else {
                    const errorData = await response.json().catch(() => null);
                    if (response.status === 403) {
                        showMessage('权限不足：只有系统管理员（级别1）可以修改字段类型', 'error');
                    } else if (errorData && errorData.message) {
                        showMessage(errorData.message, 'error');
                    } else {
                        showMessage('更新失败', 'error');
                    }
                }
            } catch (error) {
                console.error('更新字段类型失败:', error);
                showMessage('更新字段类型失败', 'error');
            }
        }

        // 删除配置
        async function deleteConfig(id) {
            if (!confirm('确定要删除这个配置吗？')) {
                return;
            }

            const authResult = await checkAuth();
            if (!authResult) return;
            const { token } = authResult;

            try {
                const response = await fetch(`/form-config/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    showMessage('配置删除成功');
                    loadConfigs();
                } else {
                    showMessage('删除失败', 'error');
                }
            } catch (error) {
                console.error('删除配置失败:', error);
                showMessage('删除配置失败', 'error');
            }
        }

        // 编辑配置（简化版，只是提示）
        function editConfig(id) {
            alert('编辑功能待实现');
        }

        // 重置表单
        function resetForm() {
            document.getElementById('configForm').reset();
            // 重新勾选必填字段
            fieldTypes.filter(ft => ft.required && ft.enabled).forEach(ft => {
                const checkbox = document.getElementById(`field-${ft.key}`);
                if (checkbox) checkbox.checked = true;
            });
        }

        // 表单提交处理
        document.getElementById('configForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const name = formData.get('name');
            const selectedFieldTypeIds = formData.getAll('fieldTypes').map(id => parseInt(id));
            
            if (selectedFieldTypeIds.length === 0) {
                showMessage('请至少选择一个字段', 'error');
                return;
            }
            
            await createConfig({ name, fieldTypeIds: selectedFieldTypeIds });
        });

        // 字段类型表单提交处理
        document.getElementById('fieldTypeForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = {
                key: formData.get('key'),
                label: formData.get('label'),
                type: formData.get('type'),
                sortOrder: parseInt(formData.get('sortOrder')),
                required: formData.has('required'),
                enabled: formData.has('enabled')
            };
            
            // 处理选项
            const options = formData.get('options');
            if (options && options.trim()) {
                data.options = options.split('\n').filter(opt => opt.trim()).map(opt => opt.trim());
            }
            
            await createFieldType(data);
        });

        // 编辑字段类型表单提交处理
        document.getElementById('editFieldTypeForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const id = parseInt(formData.get('id'));
            const data = {
                key: formData.get('key'),
                label: formData.get('label'),
                type: formData.get('type'),
                sortOrder: parseInt(formData.get('sortOrder')),
                required: formData.has('required'),
                enabled: formData.has('enabled')
            };
            
            // 处理选项
            const options = formData.get('options');
            if (options && options.trim()) {
                data.options = options.split('\n').filter(opt => opt.trim()).map(opt => opt.trim());
            }
            
            await updateFieldType(id, data);
        });

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', async function() {
            await checkAuth();
            loadUserInfo();
            loadFieldTypes();
            loadConfigs();
        });

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const addModal = document.getElementById('addFieldTypeModal');
            const editModal = document.getElementById('editFieldTypeModal');
            
            if (event.target === addModal) {
                closeAddFieldTypeModal();
            } else if (event.target === editModal) {
                closeEditFieldTypeModal();
            }
        }
    </script>
    
    <!-- Bootstrap JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>